<template>
    <div>
        <a-form @finish="handleFinish" :model="form" ref="formRef" name="basic" :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }" autocomplete="off">
            <a-row :gutter="16">
                <a-col :span="12">
                    <a-form-item label="项目名称" name="proName" :rules="[{ required: true }]">
                        <a-input-search v-model:value="form.proName" :disabled="disabled" style="width: 100%"
                            placeholder="请选择项目" @click="onSearch" @search="onSearch" />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="项目编号" name="proCode">
                        <a-input v-model:value="form.proCode" disabled style="width: 100%" placeholder="请选择项目" />

                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">

                <a-col :span="12">
                    <a-form-item label="预算单名称" :rules="[{ required: true }]" name="name">
                        <a-input v-model:value="form.name" :disabled="disabled" style="width: 100%" placeholder="" />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="预算单编号" name="code">
                        <a-input v-model:value="form.code" disabled style="width: 100%" placeholder="" />
                    </a-form-item>
                </a-col>
            </a-row>
            <!-- <a-row :gutter="16">
                <a-col :span="12">
                    <a-form-item label="项目名称" name="name">
                        <a-input v-model:value="form.name" :disabled="disabled"  style="width: 100%" placeholder="" />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="预估算名称" name="budgetname">
                        <a-input v-model:value="form.budgetname" :disabled="disabled"  style="width: 100%" placeholder="" />
                    </a-form-item>
                </a-col>
            </a-row> -->
            <a-row :gutter="16">
                <a-col :span="12">
                    <a-form-item label="预结算名称" name="settlementName" :rules="[{ required: true }]">
                        <a-input v-model:value="form.settlementName" :disabled="disabled" style="width: 100%"
                            placeholder="" />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="合作单位" name="cooperator" :rules="[{ required: true }]">
                        <a-input v-model:value="form.cooperator" :disabled="disabled" style="width: 100%"
                            placeholder="" />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="预算完成时间" name="endTime" :rules="[{ required: true }]">
                        <a-date-picker :getCalendarContainer="trigger => trigger.parentNode" valueFormat="YYYY-MM-DD hh:mm:ss" :disabled="disabled"
                            v-model:value="form.endTime" style="width: 100%" placeholder="" />
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="12">

                    <a-form-item label="负责人" name="director" :rules="[{ required: true }]">
                        <a-input v-model:value="form.directorName" :disabled="disabled" @click="showUserSelect()"
                            style="width: 100%" placeholder="" />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="成本预算总额" name="amount" :rules="[{ required: true }]">
                        <a-input-number :precision="2" :min="0"  v-model:value="form.amount" :disabled="disabled"
                            style="width: 100%" suffix="元" placeholder="" />
                    </a-form-item>
                </a-col>
            </a-row>


            <a-row :gutter="16">

                <a-col :span="12">
                    <a-form-item label="项目情况" name="remark">
                        <a-textarea v-model:value="form.remark" :disabled="disabled" style="width: 100%"
                            placeholder="" />
                    </a-form-item>
                </a-col>
            </a-row>

            <a-row :gutter="16" class="mb-2">

                <a-col :span="6" style="font-weight: 600;">
                    成本控制明细：
                </a-col>
                <a-col :span="18" class="text-right" v-if="!disabled">
                    <a-button class="ml-2" @click="addMaterial" type="primary">新增明细</a-button>
                </a-col>
            </a-row>

            <a-row :gutter="16">

                <a-col :span="24">
                    <a-table :dataSource="form.materiaList" bordered :columns="columns" :pagination="false"
                        :scroll="{ x: 1400, }">
                        <template #bodyCell="{ column, record, index }">
                            <template v-if="column.key === 'index'">
                                <div v-if="index + 1 != form.materiaList.length">
                                    {{ index + 1 }} </div>
                                <div v-else>
                                    合计
                                </div>
                            </template>
                            <template v-if="column.key === 'code'">
                                {{ record?.code || record?.material?.code }}
                            </template>
                            <template v-if="column.key === 'name'">
                                {{ record?.name || record?.material?.name }}
                            </template>


                            <template v-if="column.key === 'control'">
                                <div v-if="index + 1 != form.materiaList.length">
                                    <a-popconfirm title="确定删除此数据？" @confirm="remove(index)">
                                        <a-button type="link" danger size="small">删除</a-button>
                                    </a-popconfirm>

                                </div>
                            </template>

                            <!-- <template v-if="column.key === 'totalUnitPrice'">

                                <div v-if="index + 1 != form.materiaList.length">
                                    {{ record.unitPrice * record.quantities }}
                                </div>
                                <div v-else>
                                    22
                                </div>
                            </template> -->

                            <!-- <template v-if="column.key === 'totalCost'">
                                <div v-if="index + 1 != form.materiaList.length">
                                    {{ record.costUnitPrice * record.quantities }}
                                </div>
                                <div v-else>
                                    22
                                </div>
                            </template> -->

                        </template>
                    </a-table>

                </a-col>
            </a-row>
            <system :value="form"></system>
        </a-form>
        <projectSelection ref="proSelect" @onClose="prSelectOk" :value="form.proSelectRecords" />
        <materialSelection ref="mSelection" @onClose="mSelectOk" />
        <userSelectorPlus ref="userSelectorRef" @OnClose="userSelectorOk" />
    </div>
</template>

<script setup>
import system from '@/components/Task/system.vue'
import costApi from '@/api/pm/cost/index'
import materialSelection from '@/components/pm/materialSelection.vue'
import projectSelection from '@/components/pm/projectSelection.vue'
import userSelectorPlus from '@/components/Selector/userSelectorPlusExtend.vue'
const isShow = ref(false)
const props = defineProps({
    value: {
        type: Object,
        default: () => { }
    },
    disabled: {
        type: Boolean,
        default: () => false
    },
})
const form = ref({
});
const userSelectorRef = ref()
const showUserSelect = () => {
    userSelectorRef.value.show("")
}
const userSelectorOk = (data) => {
    form.value.directorName = data.value.directorName
    form.value.director = data.value.directorId
}
let columns = [
    {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
        width: 100,
    },
    {
        title: '物料编码',
        dataIndex: 'code',
        key: 'code',
        width: 160,
        align: 'center',
    },
    {
        title: '物料名称',
        dataIndex: 'name',
        key: 'name',
        width: 160,
        align: 'center',
    },
    {
        title: '单位',
        dataIndex: 'unit',
        key: 'unit',
        width: 140,
        align: 'center',

    },
    {
        title: '工程量',
        dataIndex: 'quantities',
        key: 'quantities', width: 140,
        align: 'center',

    },

    {
        title: '人工单价',
        dataIndex: 'laborUnitPrice',
        key: 'laborUnitPrice', width: 140,
        align: 'center',
    },
    {
        title: '人工合价',
        dataIndex: 'totalLaborCost',
        key: 'totalLaborCost', width: 140,
        align: 'center',
    },
    {
        title: '物料单价',
        dataIndex: 'unitPrice',
        key: 'unitPrice', width: 140,
        align: 'center',
    },
    {
        title: '物料合价',
        dataIndex: 'totalUnitPrice',
        key: 'totalUnitPrice', width: 140,
        align: 'center',
    },
    {
        title: '成本单价',
        dataIndex: 'costUnitPrice',
        key: 'costUnitPrice', width: 140,
        align: 'center',
    },

    {
        title: '成本总价',
        dataIndex: 'totalCost',
        key: 'totalCost', width: 140,
        align: 'center',
    },
    {
        title: '综合单价',
        dataIndex: 'synUnitPrice',
        key: 'synUnitPrice', width: 140,
        align: 'center',
    },

    {
        title: '综合总价',
        dataIndex: 'comTotalPrice',
        key: 'comTotalPrice', width: 140,
        align: 'center',
        customRender({ text, record, index, column }) {
            return `${record.comTotalPrice}`;
        }
    },
    {
        title: '操作',
        dataIndex: 'control',
        key: 'control',
        width: (!props.disabled ? 100 : 1),
        fixed: (!props.disabled ? "right" : ""),
        colSpan: (!props.disabled ? 1 : 0)
    },
]

const remove = (index) => {
    form.value.materiaList.splice(index, 1)

}

const proSelect = ref()
const onSearch = () => {
    proSelect.value.show()
}
const prSelectOk = (selectedRowKeys, selectRecords) => {
    // console.log("项目选择ok ", selectedRowKeys, selectRecords)
    form.value.proId = selectRecords[0].id;
    form.value.proCode = selectRecords[0].code;
    form.value.proName = selectRecords[0].name;
    form.value.proSelectRecords = selectRecords;
}

const mSelection = ref()
const addMaterial = () => {
    mSelection.value.show()
}

const mSelectOk = (rows) => {
    const selectedRows = JSON.parse(JSON.stringify(rows));
    selectedRows.map(x => {
        x.totalCost = x.quantities * x.costUnitPrice
        x.comTotalPrice = x.quantities * x.comUnitPrice
        x.totalLaborCost = x.quantities * x.laborUnitPrice
        x.totalUnitPrice = x.quantities * x.unitPrice
        x.comTotalPrice = x.quantities * x.synUnitPrice
        x.materialId = x.id
    })
    if (selectedRows.length > 0) {
        var sumItem = { totalCost: 0, comTotalPrice: 0, totalLaborCost: 0, totalUnitPrice: 0, comUnitPrice: 0 }
        selectedRows.map(x => {
            sumItem.totalCost += x.totalCost
            sumItem.comTotalPrice += x.comTotalPrice
            sumItem.totalLaborCost += x.totalLaborCost
            sumItem.totalUnitPrice += x.totalUnitPrice
            sumItem.comUnitPrice += x.comUnitPrice
            sumItem.isSum = true
        })
        selectedRows.push(sumItem)
    }
    form.value.materiaList = selectedRows
}
const show = (record) => {
    if (record) {
        form.value = { ...record }
        columns.splice(0, columns.length - 2)
        costApi.detail({ costBudgetId: record.id }).then((res) => {
            console.log(" costApi.detail res:", res)
            mSelectOk(res.records)
            // form.value.materiaList = res.records
        })
    } else {
        form.value = {}
    }

}
const formRef = ref(null)
const submit = () => {
    // debugger;
    formRef.value.validate().then(() => {
        handleFinish(form.value)
    }).catch((err) => {

    });
}
const handleFinish = (values) => {
    const newList = values.materiaList.splice(0, values.materiaList.length - 1)
    values.materiaList = newList
    if (!form.value.id) {
        costApi.add(values).then(() => {
            onClose(true);
        })
    } else {
        values.id = form.value.id;
        costApi.edit(values).then(() => {
            onClose(true);
        })
    }
};


const emits = defineEmits(['OnClose'])
const onClose = (refresh) => {
    form.value = {};
    emits('OnClose', refresh)
};




watch(
    () => props.value,
    (newVal, oldVal) => {
        if (newVal) {
            form.value = { ...newVal }
            if (form.value.name) {
                isShow.value = true
                columns.splice(0, columns.length - 2)
                costApi.detail({ costBudgetId: form.value.id }).then((res) => {
                    console.log(" costApi.detail res:", res)
                    mSelectOk(res.records)
                    // form.value.materiaList = res.records
                })
            } else {
                isShow.value = false
            }
        }
    },
    { deep: true, immediate: true }
)

const getData = () => {
    return new Promise((resolve, reject) => {
        formRef.value.validate().then(() => {
            if (form.value.materiaList) {
                form.value.materiaList = form.value.materiaList.filter(item => item.isSum != true)
            }
            form.value.flowCode = "FLW_COST_BUDGET"
            resolve(form.value)
        }).catch((err) => {
            reject(err)
        });
    })
}
// 重置
const resetForm = () => {
    formRef.value.resetFields()
}
defineExpose({
    getData,
    resetForm,
    show
})

</script>